var toPage;
laydate.render({
    elem: '#validationCustom22',
    type: 'datetime',
    done: function (value) {
        $('#validationCustom22').val(value);
        $('#validationCustom22').trigger('input');
    }
});
const overtimeTime = 0.166;
$(function () {
    loadCompanyList_t();
    // loadCollectionDevice();
    loadCollectionDeviceList();
    addFormValidation();
    editFormValidation();
    editDeviceConfig();
})

/*加载企业信息下拉框*/
function loadCompanyList_t() {
    getJson("/enterprise/findEnterpriseS", null, 'GET', function (res) {
        if (res.code == 200) {
            var resData = res.payload.data;
            resData.map(function (item, index) {
                item.text = item.name;
            });
            $('#company-list').selectivity({
                items: resData,
                placeholder: '选择企业'
            });
            $('#validationCustom06').selectivity({
                items: resData,
                placeholder: '选择企业'
            });
            $('#search_company').selectivity({
                items: resData,
                placeholder: '选择归属企业'
            });
        } else {
            myAlert("提示", result.message);
        }
    })
}

function companyChange(val) {
    $('#company-list-vld').val(val);
    $('#addInfoForm').data('bootstrapValidator').updateStatus('enterpise', 'NOT_VALIDATED', null).validateField('enterpise');//重置并触发字段的验证
}

function companyChange_t(val) {
    $('#validationCustom06-vld').val(val);
}

function addFormValidation() {
    $('#addInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
                        message: '设备名称只能由汉字、字母、数字、横线和下划线组成'
                    }
                }
            },
            sn: {
                validators: {
                    notEmpty: {},
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '设备编号只能由字母、数字和下划线组成'
                    },
                    threshold: 2, //设置4字符以上开始请求服务器
                    //有待验证，备注以备下次使用。
                    //bootstrap的remote验证器需要的返回结果一定是json格式的数据 :
                    //{"valid":false} //表示不合法，验证不通过
                    //{"valid":true} //表示合法，验证通过
                    remote: {//发起Ajax请求。
                        url: '../device/verificationDeviceByNumber2',//验证地址
                        data: {
                            'methodType': $('input[name="methodType"]').val(),
                            'sn': $('input[name="sn"]').val(),
                            'type': 0
                        },
                        message: '设备编号已存在',//提示消息
                        delay: 1000,//设置2秒发起名字验证
                        type: 'POST' //请求方式
                    }
                }
            }, clientId: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 3,
                        max: 255
                    },
                    threshold: 3, //设置4字符以上开始请求服务器
                    //有待验证，备注以备下次使用。
                    //bootstrap的remote验证器需要的返回结果一定是json格式的数据 :
                    //{"valid":false} //表示不合法，验证不通过
                    //{"valid":true} //表示合法，验证通过
                    remote: {//发起Ajax请求。
                        url: '../device/verificationDeviceByClientID',//验证地址
                        data: {'clientID': $('input[name="clientId"]').val()},
                        message: '主题已存在',//提示消息
                        delay: 1000,//设置2秒发起名字验证
                        type: 'POST' //请求方式
                    }
                }
            }, enterpise: {
                validators: {
                    notEmpty: {
                        message: '请选择企业',//提示消息
                    },
                }
            }
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        let status = $('#status').val();
        if (status == 0) {
            myAlert("提示", "请先测试连接");
            $('[type="submit"]').removeAttr("disabled");
            return;
        } else if (status == 2) {
            myAlert("提示", "设备连接失败");
            $('[type="submit"]').removeAttr("disabled");
            return;
        } else if (status == 3) {
            myAlert("提示", "请等设备连接完成再保存");
            $('[type="submit"]').removeAttr("disabled");
            return;
        }
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        var bv = $form.data('bootstrapValidator');
        ////使用Ajax提交表单数据
        $.ajax({
            url: "../device/saveCollectionEquipment",
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('token', sessionStorage.getItem("token"));
            },
            success: function (data) {
                if (data.code == 200) {
                    myAlert("提示", "保存成功", function () {
                        loadCollectionDevice(toPage);
                        return;
                    })
                }
                myAlert("提示", "保存失败")
            },
            error: function (data) {
                myAlert("提示", "保存失败")
            }
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

function editDeviceConfig() {
    /*修改设备信息表单验证*/
    $('#deviceConfigForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            clock: {
                validators: {
                    notEmpty: {
                        message: '请选择时间'
                    }
                }
            }, uploadTime: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 2
                    },
                    regexp: {
                        regexp: /^([1-9]|[1-5][0-9]|60)$/,
                        message: '请输入1-60的数字'
                    }
                }
            }, harmonic: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 2
                    },
                    regexp: {
                        regexp: /^([0-9]|[1-3][0-9]|40|41)$/,
                        message: '请输入0-41的数字'
                    }
                }
            }, variableFlowRatio: {
                validators: {
                    stringLength: {
                        min: 1,
                        max: 4
                    },
                    regexp: {
                        regexp: /^\+?[1-9]\d{0,3}(\.\d*)?$/,
                        message: '请输入1-9999的数字'
                    }
                }
            }, transformationRatio: {
                validators: {
                    stringLength: {
                        min: 1,
                        max: 4
                    },
                    regexp: {
                        regexp: /^\+?[1-9]\d{0,3}(\.\d*)?$/,
                        message: '请输入1-9999的数字'
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        var bv = $form.data('bootstrapValidator');
        ////使用Ajax提交表单数据
        showLoading("配置修改中");
        $.ajax({
            url: "../device/updateDeviceConfig",
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('token', sessionStorage.getItem("token"));
            },
            success: function (data) {
                if (data.code == 200) {
                    myAlert("提示", "保存成功", function () {
                        $('#deviceConfigModal').modal('hide');
                        loadCollectionDevice(toPage);
                        hideLoading();
                        return;
                    })
                }
                myAlert("提示", data.message, function () {
                    hideLoading();
                })
            },
            error: function (data) {
                hideLoading();
                myAlert("提示", data.message)
            }
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

function editFormValidation() {
    /*修改设备信息表单验证*/
    $('#editInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',

            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    },
                }
            }, clientId: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 3,
                        max: 25
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        var bv = $form.data('bootstrapValidator');
        ////使用Ajax提交表单数据
        $.ajax({
            url: "../device/updateCollectionEquipment",
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('token', sessionStorage.getItem("token"));
            },
            success: function (data) {
                if (data.code == 200) {
                    myAlert("提示", "保存成功", function () {
                        loadCollectionDevice(toPage);
                        return;
                    })
                }
                myAlert("提示", "保存失败")
            },
            error: function (data) {
                myAlert("提示", "保存失败")
            }
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

function loadCollectionDeviceList(_pageIndex) {
    $('#addInfoModal').modal('hide');
    $('#editInfoModal').modal('hide');
    $('#d_list tbody').empty();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    showLoading(LOADING);
    getJson("/device/getCollectionEquipment", {
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (result) {
        buildData(result, pageIndex);
    })
}

/* 加载采集设备信息*/
function loadCollectionDevice(_pageIndex) {
    $('#addInfoModal').modal('hide');
    $('#editInfoModal').modal('hide');
    $('#d_list tbody').empty();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    showLoading(LOADING);
    let param = $("#param-id").val();
    let company = $("#search_company").selectivity('val');
    getJson("/device/getCollectionEquipment", {
        "param": param,
        "bind": $('#bind').val(),
        "status": $('#bind_status').val(),
        company: company,
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (result) {
        buildData(result, pageIndex);
    })
}

function buildData(result, pageIndex) {
    if (result['code'] == 200) {
        let data = result['payload']['data'];
        setPage($('#page'), pageIndex, result['payload']['pages'], result['payload']['total'], function (num) {
            loadCollectionDevice(num);
        });
        let order = 1 + 10 * (pageIndex - 1);
        for (let item of data) {
            item['order'] = order++;
        }
        let dataTime;
        buildTable($('#d_list'), title, label, data, function (td, label, item) {
            switch (label) {
                case 'createTime':
                    $(td).text(getDate(item['createTime']).datetime());
                    break;
                case'isBind':
                    let sp = createElement('span', td, null, null);
                    $(sp).addClass("badge font-p14");
                    if (isNull(item['ceqNumber'])) {
                        $(sp).addClass("badge-danger");
                        $(sp).text("未绑定");
                    } else {
                        $(sp).addClass("badge-primary");
                        $(sp).text("已绑定");
                    }
                    break;
                case 'opera':
                    let config = createElement('a', td);
                    $(config).addClass('font-p24 config-option-btn');
                    $(config).attr('href', '##');
                    $(config).attr('title', '采集设备设置');
                    $(config).click(function () {
                        deviceConfig(item['id']);
                    });
                    let configIcon = createElement('i', config);
                    $(configIcon).addClass('iconfont icon-weixiu');
                    $(td).append('<div class="dropdown mx-2 d-inline">\n' +
                        '  <a class="dropdown-toggle font-p24 fresh-option-btn" href="##" title="设备复位选择" data-toggle="dropdown"><i class="iconfont icon-shuaxin1"></i></a>\n' +
                        '  <div class="dropdown-menu dropdown-menu-right">\n' +
                        '    <a class="dropdown-item" href="#" onclick="resetDevice1(\'' + item['id'] + '\')">远程复位报警信号</a>\n' +
                        '    <a class="dropdown-item" href="#" onclick="resetDevice2(\'' + item['id'] + '\')">远程重启单片机系统</a>\n' +
                        '    <a class="dropdown-item" href="#" onclick="resetDevice3(\'' + item['id'] + '\')">远程清零电能表数据</a>\n' +
                        '  </div>\n' +
                        '</div>');
                    //js方式加元素，繁琐，写一半搁置了
                    // let fresh = createElement('div', td);
                    // $(fresh).addClass('dropdown mx-2 d-inline');
                    // let freshToggle = createElement('a', fresh);
                    // $(freshToggle).addClass('dropdown-toggle font-p24 fresh-option-btn');
                    // $(freshToggle).attr({
                    //     'href': '##',
                    //     'title': '设备复位选择',
                    //     'data-toggle': 'dropdown'
                    // });
                    // let freshIcon = createElement('i', freshToggle);
                    // $(freshIcon).addClass('iconfont icon-shuaxin1');

                    let edit = createElement('a', td);
                    $(edit).addClass('font-p24');
                    $(edit).attr('href', '##');
                    $(edit).attr('title', '修改采集设备信息');
                    $(edit).click(function () {
                        editInfo(item['id']);
                    });
                    if (isNull(item['ceqNumber'])) {
                        let del = createElement('a', td);
                        $(del).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                        $(del).attr('href', '##');
                        $(del).attr('title', '删除');
                        $(del).click(function () {
                            deleteInfo(item['id']);
                        });
                        let delIcon = createElement('i', del);
                        $(delIcon).addClass('iconfont').addClass('icon-shanchuicon');
                    }
                    let editIcon = createElement('i', edit);
                    $(editIcon).addClass('iconfont').addClass('icon-bianji-');

                    break;
                case 'linkLoss':
                    dataTime = item['dataTime'];
                    if (!item['dataTime']) {
                        dataTime = item['createTime'];
                    }
                    let time1 = Number(Number(((new Date()).valueOf() - dataTime) / 1000 / 3600).toFixed(2));
                    let linkIcon = createElement('i', td);
                    let span = createElement('span', td);
                    $(linkIcon).addClass('iconfont');
                    if (time1 < overtimeTime) {//根据实际情况
                        $(span).text(' 否（状态正常）');
                        $(linkIcon).addClass('iconfont').addClass('icon-queding text-linkTrue');
                    } else {
                        $(span).text(' 是（状态异常）');
                        $(linkIcon).addClass('iconfont').addClass('icon-shanchu1 text-linkFalse');
                    }
                    break;
                case 'lossTime':
                    dataTime = item['dataTime'];
                    if (!item['dataTime']) {
                        dataTime = item['createTime'];
                    }
                    let time = Number(Number(((new Date()).valueOf() - dataTime) / 1000 / 3600).toFixed(2));
                    if (time < 0) {
                        $(td).text(0);
                    } else {
                        $(td).text(time);
                    }
                    break;
            }
        })
    }
    hideLoading();
}

/*删除设备信息*/
function deleteInfo(e) {
    myConfirm("提示", "您是否要删除此设备信息", function (res) {
        if (res) {
            getJson("/device/deleteDevice", {"id": e}, 'GET', function (result) {
                if (result.code == '200') {
                    myAlert("提示", "删除成功", function () {
                        loadCollectionDevice(toPage);
                    })
                } else {
                    myAlert("提示", result.message)
                }
            })
        }
    })
}

$("#page").paging({
    pageNo: 1,
    totalPage: 1,
    totalSize: 1,
    callback: function (num) {
    }
});

/*添加*/
function addInfo() {
    $('#addInfoForm')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    /*重写加载表单验证*/
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    addFormValidation()
    $('#not').attr("style", "display:block;");
    $('#try').attr("style", "display:none;");
    $('#success').attr("style", "display:none;");
    $('#addInfoModal').modal();
}

/*修改信息*/
function editInfo(e) {
    $('#editInfoForm')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    /*重写加载表单验证*/
    $("#editInfoForm").data('bootstrapValidator').destroy();
    $('#editInfoForm').data('bootstrapValidator', null);
    editFormValidation()
    $('#id-id').val(e);
    getJson("/device/getCollectionEquipmentById", {"id": e}, 'GET', function (result) {
        $('#validationCustom04').val(result.sn);
        $('#validationCustom05').val(result.name);
        $('#validationCustom001').val(result.clientId);
        $('#validationCustom06-vld').val(result.enterpise);
        $('#validationCustom06').selectivity('val', result.enterpise);
        $('#editInfoModal').modal();
    })
}

/*采集设备设置*/
function deviceConfig(id) {
    $('#customRadioInline51').attr('disabled', 'true');
    $('#customRadioInline52').attr('disabled', 'true');
    $('#kzwd').hide();
    $('#blb').hide();
    $('#byb').hide();
    $('#deviceConfigForm')[0].reset();//清空表单
    /*重写加载表单验证*/
    $("#deviceConfigForm").data('bootstrapValidator').destroy();
    $('#deviceConfigForm').data('bootstrapValidator', null);
    $('#device-id').val(id);
    editDeviceConfig();
    getJson("/device/getCollectionEquipmentById", {"id": id}, 'GET', function (result) {
        let clientID = result.clientId;
        $('#clientID-id').val(clientID);
        let type = clientID.substring(clientID.indexOf("/") + 1, clientID.indexOf("/") + 2);
        if (!isNull(type) && type != 4) {
            $('#wgsc').hide();
            $('#RS485').hide();
            $('#ycxb').hide();
            $('#kzwd').hide();
        }
        getJson("/device/getDeviceParamByDeviceId", {clientId: clientID}, 'GET', function (result) {
            if (result['code'] == 200) {
                let data = result['payload']['data'];
                if (!isNull(data)) {
                    if (data['RS485'] == 0) {
                        $('#customRadioInline61').prop("checked", 'checked');
                    } else if (data['RS485'] == 1) {
                        $('#kzwd').show();
                        $('#customRadioInline62').prop("checked", 'checked');
                    } else if (data['RS485'] == 2) {
                        $('#customRadioInline63').prop("checked", 'checked');
                    }
                    if (data['transformer'] == 0) {
                        $('#customRadioInline61').prop("checked", 'checked');
                    } else if (data['transformer'] == 1) {
                        $('#blb').show();
                        $('#byb').show();
                        $('#customRadioInline62').prop("checked", 'checked');
                    }
                    $("input[name='powerSupply'][value='" + data['powerSupply'] + "']").prop("checked", "checked");

                    if (!isNull(data['powerSupply']) && data['powerSupply'] == 0) {
                        $('#customRadioInline51').removeAttr("disabled");
                        $('#customRadioInline52').removeAttr("disabled");
                        $("input[name='wiring'][value='" + data['wiring'] + "']").prop("checked", "checked");
                    }
                    $("input[name='OUT1'][value='" + data['OUT1'] + "']").prop("checked", "checked");
                    $("input[name='OUT2'][value='" + data['OUT2'] + "']").prop("checked", "checked");
                    $("input[name='RS232'][value='" + data['RS232'] + "']").prop("checked", "checked");
                    $("input[name='networkUpload'][value='" + data['networkUpload'] + "']").prop("checked", "checked");
                    $("input[name='transformer'][value='" + data['transformer'] + "']").prop("checked", "checked");
                    $("input[name='microBreak'][value='" + data['microBreak'] + "']").prop("checked", "checked");
                    $('#validationCustom22').val(data['clock']);
                    $('#validationCustom23').val(data['uploadTime']);
                    $('#validationCustom25').val(data['harmonic']);
                    $('#validationCustom26').val(data['transformationRatio']);
                    $('#validationCustom27').val(data['mqttip']);
                }
                $('#deviceConfigModal').modal();
            } else {
                myAlert("提示", "获取配置失败");
            }
        })
    })

}

/*远程复位报警信号*/
function resetDevice1(id) {
    myConfirm('操作确认', '是否远程复位报警信号，该操作将不可逆', function (res) {
        if (res) {
            getJson("/device/remoteResetAlarm", {id: id}, 'GET', function (result) {
                if (result['code'] == 200) {
                    myAlert("提示", "复位报警信号发送成功")
                } else {
                    myAlert("提示", result.message);
                }
            })
        }
    })
}

/*远程重启单片机系统 */
function resetDevice2(id) {
    myConfirm('操作确认', '是否远程重启单片机系统，该操作将不可逆', function (res) {
        if (res) {
            getJson("/device/restartDevice", {id: id}, function (result) {
                if (result['code'] == 200) {
                    myAlert("提示", "重启命令发送成功")
                } else {
                    myAlert("提示", result.message);
                }
            })
        }
    })
}

/*远程清零电能表数据 */
function resetDevice3(id) {
    myConfirm('操作确认', '是否远程清零电能表数据，该操作将不可逆', function (res) {
        if (res) {
            getJson("/device/clearElectric", {id: id}, 'GET', function (result) {
                if (result['code'] == 200) {
                    myAlert("提示", "清零电能表命令发送成功")
                } else {
                    myAlert("提示", result.message);
                }
            })
        }
    })
}

/*点击测试连接展示状态*/
function connection() {
    if (!$('#addInfoForm').data('bootstrapValidator').isValid()) {
        //没有通过校验
        myAlert("提示", "请先输入必要参数,或者检查MQTT主题是否已经存在");
        return;
    }
    // let idPattern = /^[a-zA-Z]([\/\a-zA-Z0-9])+$/;
    let idPattern = /^[a-zA-Z\d\/]+$/;
    if (!idPattern.test($('#validationCustom00').val())) {
        myAlert("提示", "MQTT主题格式有误，请注意空格回车");
        return;
    }

    /*   if (!$('#validationCustom00').val()||!$('#validationCustom01').val()||!$('#validationCustom02').val()) {
           myAlert("提示","请先输入必要参数(前三项)");
           return;
       }*/
    $('#not').attr("style", "display:none;");
    $('#success').attr("style", "display:none;");
    $('#try').attr("style", "display:block;");
    $('#status').val(3);
    getJson("/device/connectionDevice", {"number": $('#validationCustom00').val()}, 'GET', function (result) {
        if (result.code == 200) {
            $('#try').attr("style", "display:none;");
            $('#success').attr("style", "display:block;");
            $('#status').val(1);
        } else {
            $('#try').attr("style", "display:none;");
            $('#not').attr("style", "display:block;");
            $('#status').val(2);
        }
    })
}

$("#validationCustom00").change(function () {
    $('#not').attr("style", "display:block;");
    $('#success').attr("style", "display:none;");
    $('#try').attr("style", "display:none;");
    $('#status').val(0);
});

function disableLabel(index) {
    if (index == 1) {
        $('#customRadioInline51').prop('checked', false);
        $('#customRadioInline52').prop('checked', false);
        $('#customRadioInline51').attr('disabled', 'true');
        $('#customRadioInline52').attr('disabled', 'true');
    } else {
        $('#customRadioInline51').removeAttr("disabled");
        $('#customRadioInline52').removeAttr("disabled");
    }
}